<template>
    <n-modal
        title="分配应用"
        style="width: 50%"
        :mask-closable="false"
        :close-on-esc="false"
        preset="card"
        :show="show"
        @close="close"
        :on-after-enter="init"
        :on-after-leave="destroy"
    >
        <n-data-table
            table-layout="fixed"
            :bordered="false"
            :columns="columns"
            :data="records"
            :row-key="(row: BaseApp) => row.id"
            :default-checked-row-keys="checkedKeys"
            @update:checked-row-keys="handleCheck"
            remote
        />
        <template #footer>
            <n-space justify="end">
                <n-button type="info" @click="handleConfirmOnClick">确认</n-button>
                <n-button @click="close">关闭</n-button>
            </n-space>
        </template>
    </n-modal>
</template>
<script lang="ts" setup>
import type { DataTableColumn } from 'naive-ui'
import { reactive, toRefs, PropType } from 'vue'
import { getAppList } from '@/api/base/app'
import { getRoleAppRelationList, postRoleAppRelation } from '@/api/base/roleAppRelation'
import { IMessage } from '@/utils/message'

const state = reactive({
    records: [] as Array<BaseApp>,
    checkedKeys: [] as Array<number>
})

const {
    records,
    checkedKeys
} = toRefs(state)

const props = defineProps({
    show: {
        type: Boolean
    },
    row: {
        type: Object as PropType<BaseRole>,
        required: true
    }
})

const emits = defineEmits<{
    (e: 'handleSelectOnClick'): void,
    (e: 'handleCloseOnClick'): void
}>()

const columns: Array<DataTableColumn<BaseApp>>= [
    { type: 'selection' },
    { key: 'id', title: '编号' },
    { key: 'code', title: '码值' },
    { key: 'name', title: '名称' }
]

const handleCheck = (keys: Array<string | number>) => {
    state.checkedKeys = keys as Array<number>
}

const init = async () => {
    const { data: list } = await getAppList()
    state.records = list

    const relation: BaseRoleAppRelation = { roleId: props.row.id } 
    const { data: checkedList } = await getRoleAppRelationList(relation)
    list.filter(app => {
        return checkedList.map(ele => ele.appId).includes(app.id)
    }).forEach(app => {
        state.checkedKeys.push(app.id)
    })
}

const handleConfirmOnClick = async () => {
    const params = {
        roleId: props.row.id,
        appIds: state.checkedKeys
    }
    const { message } = await postRoleAppRelation(params)
    IMessage({ content: message })
    close()
    select()
}

const select = () => {
    emits('handleSelectOnClick')
}

const close = () => {
    emits('handleCloseOnClick')
}

const destroy = () => {
    state.checkedKeys = []
}

</script>